package com.twu.biblioteca.Library;

import com.google.common.primitives.Ints;
import com.twu.biblioteca.command.*;
import com.twu.biblioteca.service.BookService;
import com.twu.biblioteca.service.LoginService;
import com.twu.biblioteca.service.MovieService;
import com.twu.biblioteca.view.MessageView;

import java.io.BufferedReader;
import java.util.List;

import static java.util.Arrays.asList;

public class Library {

    private final int MAIN_MENU_COMMAND = 1;
    private final int SHOW_ALL_BOOKS_COMMAND = 2;

    private final BookService bookService;
    private final LoginService loginService;
    private final MovieService movieService;
    private MessageView messageView;
    private BufferedReader reader;
    private User user;

    private List<Command> commands;

    public Library(MessageView messageView, BookService bookService, LoginService loginService,
                   MovieService movieService, BufferedReader reader) {
        this.messageView = messageView;
        this.bookService = bookService;
        this.loginService = loginService;
        this.movieService = movieService;
        this.reader = reader;
        this.user = new User();
        initCommandList();
    }

    private void initCommandList() {
        commands = asList(
                new Exit(messageView),
                new MainMenu(messageView),
                new ShowAllBooks(bookService, messageView),
                new ShowAvailableBooks(bookService, messageView),
                new Login(loginService, user, reader, messageView),
                new CheckoutBook(bookService, user, messageView, reader),
                new ReturnBook(bookService, messageView, user, reader),
                new ShowAvailableMovies(movieService, messageView),
                new CheckoutMovie(movieService, messageView, user, reader),
                new ShowPersonalInformation(messageView, user));
    }

    public void welcome() {
        messageView.showWelcomeMessage();
        commands.get(SHOW_ALL_BOOKS_COMMAND).execute();
        commands.get(MAIN_MENU_COMMAND).execute();
    }

    public void start() {
        Command command;
        do {
            messageView.showMessage(MessageView.OPERATION_MESSAGE);
            command = getCommand();
            command.execute();
        } while (!(command instanceof Exit));
    }

    public Command getCommand() {
        try {
            return commands.get(Ints.tryParse(reader.readLine()));
        } catch (Exception e) {
            return new InvalidOption(messageView);
        }
    }


}